import React from 'react';
import BasicLayout from "@/src/layouts";
import Nav from "@components/nav";
import { Col, Form, Input, message, Row, Select, Space, Upload, Button, DatePicker, Radio } from 'antd';
import { LoadingOutlined, PlusOutlined } from "@ant-design/icons";
import API from "@common/api.js";
import './infoEdit.less'
import userStore from "../../common/userStore";
import { withRouter } from 'react-router-dom';
import moment from 'moment';

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

function beforeUpload(file) {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG/PNG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M;
}

const config = {
  rules: [
    {
      type: 'object',
      required: false,
      message: 'Please select time!',
    },
  ],
};


class AccountInfoEdit extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      imageUrl: userStore.getState().avatar,
      username: userStore.getState().username,
      gender: userStore.getState().sex,
      birthday: userStore.getState().birthday,
      introduction: userStore.getState().userdetail,
      isEdit: false,
    }
    this.handleChange = this.handleChange.bind(this);
    this.handleChange2 = this.handleChange2.bind(this);
    this.onFinish = this.onFinish.bind(this);

    this.jumpToLogin = this.jumpToLogin.bind(this);
    userStore.subscribe(this.jumpToLogin);
  }

  jumpToLogin() {
    if (!userStore.getState()['isLogin'])
      this.props.history.push("/login")

  }

  handleChange(info) {
    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, imageUrl =>
        this.setState({
          imageUrl: imageUrl,
          loading: false,
        }),
      );
    }
  }

  handleChange2(e) {
    this.setState({
      // value: e.target.value,
      isEdit: true,
    });
  }

  onFinish(values) {
    //values['date-picker'].format('YYYY-MM-DD');
    console.log('Received values of form: ', values.date);
    this.setState({
      username: values.username,
      gender: values.gender,
      birthday: values.datePicker,
      introduction: values.introduction,
    })
    let birthday_mo = moment(values.datePicker);
    // birthday_mo.format("YYYY-MM-DD");
    API.updateUserInfo({
      username: values.username,
      sex: values.gender,
      birthday: birthday_mo.format("YYYY-MM-DD"),
      description: values.introduction,
    }); //待修改
  }

  componentDidMount() {
    API.getUserInfo().then(response => {
      console.log("$$$$$$$$$$$$$$$", response);
      response = response.data;
      this.setState({
        imageUrl: response.avatar,
        username: response.username,
        gender: response.sex,
        birthday: response.birthday,
        introduction: response.userdetail,
      });
      console.log(this.state);
    });
  }

  render() {
    console.log(this.state);
    const { loading, imageUrl } = this.state;
    const uploadButton = (
      <div>
        {loading ? <LoadingOutlined /> : <PlusOutlined />}
        <div style={{ marginTop: 8 }}>Upload</div>
      </div>
    )
    return (
      <div id="accountInfoEditorContainer">
        <BasicLayout header={<Nav />}>
          <br />
          <Row justify="left" align={"bottom"} gutter={[208, { xs: 8, sm: 16, md: 24, lg: 32 }]}>
            <Col span={4} push={9}>
              <Upload
                name="avatar"
                listType="picture-card"
                // className="avatar-uploader"
                showUploadList={false}
                action={API.getUploadProfileAddress()}
                beforeUpload={beforeUpload}
                onChange={this.handleChange}
              >
                {imageUrl ? <img id="avatar" src={imageUrl} alt="avatar" /> : uploadButton}
              </Upload>
            </Col>
          </Row>
          <Row justify="center" align="middle">
            <Col span={16} push={1}>
              <div>
                <Form name="complex-form" onFinish={this.onFinish} labelCol={{ span: 6 }}
                  wrapperCol={{ span: 16 }} onChange={this.handleChange2}>
                  {/* <Form.Item
                    id="accountInfoEditUser"
                    label="用户名"
                    name="username"
                    rules={[{ required: false, message: '请设置用户名' }]}
                  >
                    <Input style={{ width: 160 }}
                      value={this.state.username}
                      onChange={this.handleChange2}
                      placeholder="" />
                  </Form.Item> */}
                  {/*<Tooltip title="Useful information">
                                            <Typography.Link href="#API">Need Help?</Typography.Link>
                                        </Tooltip>*/}
                  <Form.Item name="gender" label="性别">
                    <Radio.Group value={this.state.gender}>
                      <Radio value={1}>男</Radio>
                      <Radio value={0}>女</Radio>
                      <Radio value={-1}>不愿透露</Radio>
                    </Radio.Group>
                  </Form.Item>
                  <Form.Item name="datePicker" label="生日" {...config}>
                    <DatePicker value={this.state.birthday} />
                  </Form.Item>
                  <Form.Item name='introduction' label="个人简介">
                    <Input.TextArea value={this.state.introduction} />
                  </Form.Item>
                  <Form.Item label=" " colon={false}>
                    <Button type="primary" htmlType="submit" disabled={!(this.state.isEdit)}>
                      提交
                    </Button>
                  </Form.Item>
                </Form>
              </div>
            </Col>
          </Row>
        </BasicLayout>
      </div>
    );
  }

}
export default withRouter(AccountInfoEdit);